package cn.gson.crm.controller.beforesale;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.gson.crm.model.dao.CompetitorDao;
import cn.gson.crm.model.dao.CustomerDao;
import cn.gson.crm.model.dao.EmployeeDao;
import cn.gson.crm.model.dao.OpportunityDao;
import cn.gson.crm.model.entity.Competitor;
import cn.gson.crm.model.entity.Customer;
import cn.gson.crm.model.entity.Employee;
import cn.gson.crm.model.entity.SalesOpportunity;

@Controller
@RequestMapping("com")
public class CompetitorController {

	@Autowired
	EmployeeDao empDao;
	
	@Autowired
	CustomerDao cusDao;
	
	@Autowired
	CompetitorDao comDao;
	
	@Autowired
	OpportunityDao oppDao;
	
	
	@RequestMapping
	public String init() {
		return "beforesale/competitor";
	}
	
	@RequestMapping("list")
	@ResponseBody
	public Map<String, Object> list(@RequestParam(defaultValue = "1")int page,
			@RequestParam(defaultValue = "10")int rows,
			HttpServletRequest req
			){
		Employee emp = (Employee) req.getSession().getAttribute("employee");
		Long empid = emp.getId();
		Map<String, Object> data = new HashMap<>();
		PageRequest pr = new PageRequest(page - 1, rows, new Sort(Direction.DESC,"id"));
		Page<Competitor> com = null;
		//判断职位(roles)，如果是销售人员则显示他所关联的客户有关的竞争对手
		if (emp.getRole().getRoleName().equals("销售员")) {
			com = comDao.findByEmp(empid,pr);
		}else {
			//如果是管理人员，则显示所有未删除的
			com = comDao.findByIsDelete(false,pr);
		}
		data.put("rows", com.getContent());
		data.put("total", com.getTotalElements());
		return data;
	}
	
	//加载竞争对手列表里的弹窗
	@RequestMapping({"comform","comform/{id}"})
	public String demandForm(@PathVariable(required=false) Long id,Model model){
		
		if (id != null) {
			model.addAttribute("c",comDao.findOne(id));
		}
		
		return "beforesale/competitor/competitorform";
	}
	
	@RequestMapping("save")
	@ResponseBody
	@Transactional
	public JSONObject save(@Valid Competitor competitor,Long saleid,BindingResult br) {
		JSONObject result = new JSONObject();
		
		if (br.hasErrors()) {
			result.put("err", "校验失败！");
		}else {
			SalesOpportunity opp = oppDao.findOne(saleid);
			competitor.setSalesOpp(opp);
			comDao.save(competitor);
			result.put("success", true);
		}
		return result;
	}
	
	
	/**
	 * 不在数据库删除此条信息
	 * 只是将是否删除（isDelete）这个字段改成true，代表已删除
	 * @param id
	 * @return
	 */
	@GetMapping("delete/{id}")
	@ResponseBody
	public Map<String, Object> delete(@PathVariable Long id) {
		
		Map<String, Object> data = new HashMap<>();
		
		try {
			Competitor competitor = comDao.findOne(id);
			competitor.setDelete(true);
			comDao.save(competitor);
			data.put("success", true);
			
		} catch (Exception e) {
			e.printStackTrace();
			data.put("success", false);
			data.put("errorMsg", e.getMessage());
		}
		return data;
	}
}
